<template>
  <div class="user-index">
    <el-form ref="formRef" :inline="true" :model="queryParams" class="demo-form-inline">
      <el-form-item label="用户名称">
        <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable />
      </el-form-item>
      <el-form-item label="手机号码">
        <el-input v-model="queryParams.phonenumber" placeholder="请输入用户手机号码" clearable />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="请选择用户状态" clearable style="width: 240px">
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" @change="handleDateRangeChange" value-format="YYYY-MM-DD"
          type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" />
      </el-form-item> -->
      <el-row>
        <el-form-item>
          <el-button v-p="['system:user:query']" type="primary" @click="searchEvent">搜索</el-button>
          <el-button type="default" @click="resetEvent">重置</el-button>
          <el-button v-p="['system:user:add']" type="primary" plain @click="handleAdd">新增</el-button>
          <el-button
            v-p="['system:user:edit']"
            type="success"
            plain
            @click="handleUpdate"
            :disabled="selected.length > 1 || !selected.length"
          >
            修改
          </el-button>
          <el-button
            v-p="['system:user:remove']"
            type="danger"
            plain
            @click="deleteEvent()"
            :disabled="!selected.length"
            :loading="deleteLoading"
          >
            删除
          </el-button>
          <el-button type="info" plain @click="handleAuthRole">分配角色</el-button>
        </el-form-item>
      </el-row>
    </el-form>
    <el-table v-loading="loading" ref="userTableRef" :data="userList" @selection-change="handleSelectionChange" height="90%">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="用户编号" align="center" key="userId" prop="userId" />
      <el-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true" />
      <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true" />
      <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" :show-overflow-tooltip="true" />
      <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" />
      <el-table-column label="状态" align="center" key="status">
        <template v-slot="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template v-slot="scope"> {{ scope.row.createTime.split(" ")[0] }} </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="400" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <template v-if="!scope.row.admin">
            <el-button v-p="['system:user:edit']" type="primary" link @click="handleUpdate(scope.row)">修改</el-button>
            <el-button v-p="['system:user:remove']" type="primary" link @click="deleteEvent(scope.row.userId)">删除</el-button>
            <el-button type="primary" link @click="handleAuthRole(scope.row)">分配角色</el-button>
            <el-button v-p="['system:user:resetPwd']" type="primary" link @click="restPasswordEvent(scope.row)">
              重置密码
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @update:page="handlePageChange"
      @update:limit="handlePageSizeChange"
    />
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="formDataRef" :model="formData" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="formData.nickName" placeholder="请输入用户昵称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptId">
              <el-tree-select
                v-model="formData.deptId"
                :data="options"
                check-strictly
                :props="treeProps"
                :render-after-expand="false"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="formData.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="!isHide">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="formData.userName" placeholder="请输入用户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!isHide">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="formData.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="formData.sex" placeholder="请选择性别">
                <el-option v-for="item in sexOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="formData.status">
                <el-radio v-for="item in userOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="岗位">
              <el-select v-model="formData.postIds" collapse-tags collapse-tags-tooltip multiple placeholder="请选择岗位">
                <el-option
                  v-for="item in postOptions"
                  :key="item.postId"
                  :label="item.postName"
                  :value="item.postId"
                  :disabled="item.status === '1'"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select v-model="formData.roleIds" collapse-tags collapse-tags-tooltip multiple placeholder="请选择角色">
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                  :disabled="item.status === '1'"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="formData.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer" style="text-align: right">
          <el-button type="primary" @click="submitForm(formDataRef)">确 定</el-button>
          <el-button @click="cancel(formDataRef)">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="重置密码" v-model="visible" width="600px" append-to-body>
      <el-form ref="passwordDataRef" :model="passwordData" :rules="passwordRules" label-width="80px">
        <el-form-item label="密码" prop="password">
          <el-input v-model="passwordData.password" type="password" placeholder="请输入密码" maxlength="30" />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer" style="text-align: right">
          <el-button type="primary" @click="savePassword(passwordDataRef)">确 定</el-button>
          <el-button @click="closeEvent(passwordDataRef)">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import type { DeptItem } from "@/typings";
import type { FormInstance, FormRules } from "element-plus";
import {
  delUserApi,
  deptTreeApi,
  getUserByIdApi,
  resetPasswordApi,
  roleListApi,
  systemUserApi,
  updateUserApi,
  userListApi,
  userStatusApi,
  getPostOptionSelect
} from "@/api";
import { reactive, ref, onMounted } from "vue";
import router from "@/routers";
import { ElMessage, ElMessageBox } from "element-plus";
import md5 from "md5";
import Pagination from "@/components/pagination/Pagination.vue";

const total = ref(0);

const treeProps = ref({
  label: "label",
  value: "id"
});

// 表单
const formRef = ref<FormInstance>();

// 查询参数
const queryParams = reactive({
  userName: "",
  phonenumber: "",
  status: "",
  pageNum: 1,
  pageSize: 10
});

// 搜索
const searchEvent = () => {
  getUserList();
};

// 重置
const resetEvent = () => {
  queryParams.userName = "";
  queryParams.phonenumber = "";
  queryParams.status = "";
  getUserList();
};

// 岗位
const postOptions = ref<any[]>([]);
const getPostOptions = async () => {
  try {
    const res = await getPostOptionSelect();
    if (res.code === 200) {
      postOptions.value = res.data;
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    ElMessage.error("获取岗位数据失败");
  }
};

// 角色
const roleOptions = ref<any[]>([]);
const getRoleOptions = async () => {
  try {
    const res = await roleListApi({
      pageNum: 1,
      pageSize: 500
    });
    if (res.code === 200) {
      roleOptions.value = res.data;
      return;
    }
    ElMessage.error(res.message);
  } catch (error) {
    ElMessage.error("获取角色数据失败");
  }
};

// 获取用户列表
const userList = ref<DeptItem[]>([]);
const getUserList = async () => {
  try {
    const res = await userListApi(queryParams);
    if (res.code === 200) {
      userList.value = res.data;
      total.value = res.total as number;
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    ElMessage.error("获取用户数据失败");
  }
};

// 多选
const selected = ref<string[]>([]);
const userTableRef = ref<any>();
const handleSelectionChange = (data: any) => {
  selected.value = data.map((item: any) => {
    return item.userId;
  });
};

// 选择状态
const handleStatusChange = async (row: any) => {
  loading.value = true;
  try {
    const res = await userStatusApi({ userId: row.userId, status: row.status });
    if (res.code === 200) {
      ElMessage.success("修改成功");
      getUserList();
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    ElMessage.error("修改用户状态失败");
  } finally {
    loading.value = false;
    getUserList();
  }
};

const loading = ref(false);

// 新增
const handleAdd = async () => {
  await getRoleOptions();
  title.value = "新增用户";
  open.value = true;
  isHide.value = false;
  formRef.value?.resetFields();
  formData.value.password = "123456";
};
// 修改
const isHide = ref(false);
const handleUpdate = async (row?: any) => {
  try {
    isHide.value = true;
    title.value = "修改用户";
    const userId = row.userId || selected.value;
    const res = await getUserByIdApi(userId);
    if (res.code === 200) {
      formData.value = { ...res.data.user };
      formData.value.postIds = res.data.postIds;
      formData.value.roleIds = res.data.roleIds;
      open.value = true;
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    ElMessage.error("修改用户数据失败");
  }
};

// 删除
const deleteLoading = ref(false);
const deleteEvent = (id?: string) => {
  deleteLoading.value = true;
  if (id) {
    selected.value.push(id);
  }
  try {
    ElMessageBox.confirm("确定删除所勾选的用户吗？删除之后数据将无法恢复", "系统提示", {
      type: "warning"
    })
      .then(async () => {
        // 调用删除接口
        try {
          const res = await delUserApi(selected.value.join(","));
          if (res.code === 200) {
            ElMessage.success("删除成功");
            getUserList();
          } else {
            ElMessage.error(res.message);
          }
        } catch (error) {
          ElMessage.error("删除用户数据失败");
        } finally {
          deleteLoading.value = false;
          selected.value = [];
        }
      })
      .finally(() => {
        deleteLoading.value = false;
      });
  } catch (error) {
    ElMessage.error("删除失败");
  }
};

// 分配角色
const handleAuthRole = (row: any) => {
  const userId = row.userId;
  router.push("/system/user-auth/role/" + userId);
};

// 弹窗表单
const title = ref("");
const open = ref(false);
const formDataRef = ref<FormInstance>();
const formData = ref<any>({
  nickName: "",
  userName: "",
  phonenumber: "",
  email: "",
  password: "123456",
  sex: "",
  status: "0",
  deptId: null,
  remark: ""
});
const rules = reactive<FormRules>({
  userName: [{ required: true, message: "用户名称不能为空", trigger: "blur" }],
  nickName: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  password: [{ required: true, message: "用户密码不能为空", trigger: "blur" }],
  deptId: [{ required: true, message: "归属部门不能为空", trigger: "blur" }]
});

// 用户状态
const userOptions = ref([
  { value: "0", label: "正常" },
  { value: "1", label: "停用" }
]);

// 性别
const sexOptions = ref([
  { value: "0", label: "男" },
  { value: "1", label: "女" },
  { value: "2", label: "未知" }
]);

const visible = ref(false);
const passwordDataRef = ref<FormInstance>();
const passwordData = ref({
  password: ""
});
const passwordRules = reactive<FormRules>({
  password: [{ required: true, message: "密码不能为空", trigger: "blur" }]
});
const userId = ref();
const restPasswordEvent = (row: any) => {
  userId.value = row.userId;
  visible.value = true;
};
const savePassword = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid: boolean) => {
    if (!valid) return;
    try {
      const res = await resetPasswordApi({ userId: userId.value, password: md5(passwordData.value.password) });
      if (res.code === 200) {
        ElMessage.success("密码重置成功");
        visible.value = false;
        formEl.resetFields();
        getUserList();
      } else {
        ElMessage.error(res.message);
      }
    } catch (error) {
      ElMessage.error("密码重置失败");
    }
  });
};
const closeEvent = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  visible.value = false;
  formEl.resetFields();
};

// 新增
const saveUser = async () => {
  try {
    const query = { ...formData.value, password: md5(formData.value.password) };
    const res = await systemUserApi(query);
    if (res.code === 200) {
      getUserList();
      ElMessage.success("新增成功");
      open.value = false;
      formData.value.password = "123456";
      formDataRef.value?.resetFields();
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    ElMessage.error("新增用户数据失败");
  }
};

// 修改
const updateUser = async () => {
  loading.value = true;
  try {
    const res = await updateUserApi(formData.value);
    if (res.code === 200) {
      loading.value = false;
      ElMessage.success("修改成功");
      open.value = false;
      formData.value = {};
      isHide.value = false;
      getUserList();
      formDataRef.value?.resetFields();
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    ElMessage.error("修改失败");
  } finally {
    loading.value = false;
  }
};

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid: boolean) => {
    if (!valid) return;
    if (formData.value.userId) {
      // 修改
      updateUser();
    } else {
      // 新增
      saveUser();
    }
  });
};

// 取消表单
const cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  formData.value = {};
  isHide.value = false;
  formData.value.password = "123456";
  open.value = false;
  getUserList();
};

// 获取部门树
const options = ref([]);
const getDeptTree = async () => {
  try {
    const res = await deptTreeApi();
    if (res.code === 200) {
      options.value = res.data;
    } else {
      ElMessage.error(res.message);
    }
  } catch (error) {
    ElMessage.error("获取部门数据失败");
  }
};

// 分页
const handlePageChange = (page: number) => {
  queryParams.pageNum = page;
  getUserList();
};

const handlePageSizeChange = (size: number) => {
  queryParams.pageSize = size;
  getUserList();
};

onMounted(() => {
  getUserList();
  getDeptTree();
  getPostOptions();
});
</script>

<style lang="scss" scoped>
.user-index {
  width: 100%;

  .demo-form-inline .el-input {
    --el-input-width: 220px;
  }

  .demo-form-inline .el-select {
    --el-select-width: 220px;
  }
}
</style>
